package com.yimingkeji.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/11/21 19:33
 */
@SpringBootApplication
@RestController
public class ConfigApp {

    @RequestMapping("/")
    String home() {
        return "Hello World";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ConfigApp.class, args);
    }

    //@Value("myconfig.user.name")//结果：name=myconfig.user.name 不会从配置取值，相当于直接赋值
    @Value("${myconfig.user.name}") //结果 配置中的姓名
    private String name;
    @Value("${myconfig.user.sex}")
    private int sex;
    @Value("${myconfig.user.age}")
    private int age;


    @Autowired
    User user;
    @Autowired
    Environment env;
    @GetMapping("/user")
    String user() {
        StringBuilder sb = new StringBuilder();
        sb.append("@Value形式获取配置参数：\n");
        sb.append(String.format("name=%s, sex=%s, age=%s \n", name, sex, age));
        sb.append("\n\n---------------------------------------\n\n");
        sb.append("从配置类中获取配置：\n");
        sb.append(user);
        sb.append("\n\n---------------------------------------\n\n");
        sb.append("从Environment中获取配置：\n");
        sb.append(env.getProperty("myconfig.user.name"));
        return sb.toString();
    }

    @Value("${myconfig.arr}")
    private String[] arr;
    @Value("${myconfig.list}")
    private List<String> list;
    //@Value("${myconfig.map}") //------> 会报错，需要通过配置类获取
    //private Object map;

    @Autowired private MyConfig myConfig;
    @GetMapping("/coll")
    public String getArr(){
        return "arr: " + arr[0] + ","+arr[1] + "\nlist="+ list + "\nmap=" + myConfig.getMap();
    }

    @Autowired RandomConfig randomConfig;
    @GetMapping("/random")
    String random(){
        StringBuilder sb = new StringBuilder();
        sb.append("随机数:\n");
        sb.append(String.format("random.value：%s \n", randomConfig.getStr()));
        sb.append(String.format("random.int：%s \n", randomConfig.getNum()));
        sb.append(String.format("random.long：%s \n", randomConfig.getNum1()));
        sb.append(String.format("random.int(10,99)：%s \n", randomConfig.getNum2()));
        sb.append(String.format("random.uuid：%s \n", randomConfig.getUuid()));
        return sb.toString();
    }

}
